package com.gwc.schedule.controller;

import com.gwc.schedule.common.Result;
import com.gwc.schedule.pojo.SysSchedule;
import com.gwc.schedule.service.SysScheduleService;
import com.gwc.schedule.service.impl.SysScheduleServiceImpl;
import com.gwc.schedule.util.WebUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(
        urlPatterns = {"/schedule/*"}
)
public class SysScheduleController extends BaseController{
    private SysScheduleService scheduleService = new SysScheduleServiceImpl();

    /**
     * 删除个人行程
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void deleteSchedule(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int sid = Integer.parseInt(req.getParameter("sid"));
        scheduleService.deleteSchedule(sid);
        WebUtil.writeJson(resp,Result.ok(null));
    }

    /**
     * 更新用户日程，进行保存
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updateSchedule(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SysSchedule sysSchedule = WebUtil.readJson(req, SysSchedule.class);
        // 调用服务层，更新数据
        scheduleService.updateSchedule(sysSchedule);

        // 响应成功
        WebUtil.writeJson(resp,Result.ok(null));
    }

    /**
     * 根据uid帮助用户新增一个空白日程，方便用户在此基础上进行修改
     * @param req
     * @param resq
     */
    public void addScheduleByUid(HttpServletRequest req, HttpServletResponse resq){
        int uid = Integer.parseInt(req.getParameter("uid"));
        // 调用服务层方法，默认为当前用户增加一个默认空数据
        scheduleService.addScheduleByUid(uid);
        Result result = Result.ok(null);
        WebUtil.writeJson(resq,result);
    }

    /**
     * 根据uid查询用户所有日程
     * @param req
     * @param resq
     */
    public void findAllScheduleByUid(HttpServletRequest req, HttpServletResponse resq){
//        System.out.println("add schedule");
        int uid = Integer.parseInt(req.getParameter("uid"));
        // 调用服务层方法，查询日常表
        List<SysSchedule> itemList = scheduleService.findAllScheduleByUid(uid);
        // 将日程信息装入result,转换JSON给客户端
        Map<String,Object> data = new HashMap();
        data.put("itemList", itemList);
        WebUtil.writeJson(resq, Result.ok(data));
    }

}
